import os
import sys
import time

from PyQt5.QtCore import QThread, pyqtSignal, QDateTime, Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, QStatusBar, QLabel, QHBoxLayout, QDockWidget

from workspace.Project.UI.components.py_ui_compoment_log import UiComponentLog
from workspace.Project.UI.components.py_ui_component_log_cfg import UiComponentLogCfgForm
from workspace.Project.UI.ui_base.py_ui_abstract import AbstractMainForm
from workspace.Project.UI.components.NvmGeneraView import NvmGeneraView
from workspace.Project.UI.components.interactionView import Ui_InteractionView


class DockWidget(QDockWidget):
    def __init__(self, title, parent=None):
        super().__init__(title, parent)
        self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
        self.setFixedSize(parent.size())

        self._is_closed = False

    def closeEvent(self, event):
        self._is_closed = True

    def is_closed(self):
        return self._is_closed


class UiMainForm(AbstractMainForm):
    signal_ui_main = pyqtSignal(object)

    # 重写关闭窗体事件, 释放资源
    def closeEvent(self, event):
        print('主窗口关闭')
        self._back_time.quit()
        if self.childEvent == 'Close':
            self.childEvent = None
            event.ignore()
        else:
            event.accept()

    def __init__(self, main_window, cwd):
        super(UiMainForm, self).__init__(ui_name='ui_main', ui_version='v1.0.0')
        self.childEvent = None
        self.cwd = cwd
        self._set_ui()  # 初始化界面

    def _set_ui(self):
        self.setWindowTitle('mcu_tools')  # 设置标题
        # self.showMaximized()
        self.resize(1600, 800)
        self.setWindowIcon(QIcon('./resource/spyder.ico'))
        self._createMenuBar()
        self._createToolBar()
        self._createStatusBar()
        self._start_date_time()

        self.layout = QHBoxLayout()
        self.setLayout(self.layout)

    def _createMenuBar(self):
        menuBar = self.menuBar()

        # 建立文件菜单栏
        file_menu = menuBar.addMenu(QIcon('./resource/None.png'), '文件')
        file_new = QAction(QIcon('./resource/None.png'), '新建', self)
        file_new.setShortcut('Ctrl+N')
        file_open = QAction(QIcon('./resource/None.png'), '打开', self)
        file_save = QAction(QIcon('./resource/None.png'), '保存', self)
        file_exit = QAction(QIcon('./resource/None.png'), '退出', self)
        file_menu.addAction(file_new)
        file_menu.addAction(file_open)
        file_menu.addAction(file_save)
        file_menu.addAction(file_exit)

        # 建立组件菜单栏
        component_menu = menuBar.addMenu(QIcon('./resource/None.png'), '组件')
        self.component_list = []

        component_log = QAction(QIcon('./log.png'), '日志组件', self)
        self.component_log = UiComponentLog(self.cwd)
        self.docklogView = QDockWidget('日志组件', self)
        self.docklogView.setWidget(self.component_log)
        self.docklogView.setFloating(False)
        self.addDockWidget(Qt.RightDockWidgetArea, self.docklogView)
        self.docklogView.hide()
        self.component_list.append({'name': '日志组件', 'object': self.docklogView})
        self.component_log.signal_component_log.connect(self.slot_fun)

        component_TT = QAction(QIcon('./TT.png'), 'TT组件', self)
        self.dockTTView = QDockWidget('TT组件', self)
        self.dockTTView.setWidget(UiComponentLogCfgForm(self.cwd))
        self.dockTTView.setFloating(False)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dockTTView)
        self.dockTTView.hide()
        self.component_list.append({'name': 'TT组件', 'object': self.dockTTView})

        component_NVM = QAction(QIcon('./NVM.png'), 'NVM组件', self)
        self.dockNVMView = QDockWidget('NVM组件', self)
        self.dockNVMView.setWidget(NvmGeneraView(self.cwd))
        self.dockNVMView.setFloating(False)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dockNVMView)
        self.dockNVMView.hide()
        self.component_list.append({'name': 'NVM组件', 'object': self.dockNVMView})
        
        component_Interaction = QAction(QIcon('./Interaction.png'), 'Interaction组件', self)
        self.dockInteractonView = QDockWidget('Interaction组件', self)
        self.dockInteractonView.setWidget(Ui_InteractionView(self.cwd))
        self.dockInteractonView.setFloating(False)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dockInteractonView)
        self.dockInteractonView.hide()
        self.component_list.append({'name': 'Interaction组件', 'object': self.dockInteractonView})

        component_menu.addAction(component_log)
        component_menu.addAction(component_TT)
        component_menu.addAction(component_NVM)
        component_menu.addAction(component_Interaction)

        # 建立帮助菜单栏
        help_menu = menuBar.addMenu(QIcon('./resource/help.png'), '帮助')
        help_about = QAction(QIcon('./log.png'), '关于', self)
        help_menu.addAction(help_about)

        # 统一绑定槽函数
        menuBar.triggered[QAction].connect(self._menu_file_click_slot)

    def _createToolBar(self):
        tool_1 = self.addToolBar('工具栏1')
        tool_2 = self.addToolBar('工具栏2')
        calculator_act = QAction(QIcon('./Icon/spyder.ico'), '计算器', self)
        tool_1.addAction(calculator_act)

        tool_1.actionTriggered[QAction].connect(self._tools_file_click_slot)

    def _createStatusBar(self):
        self.statusBar = QStatusBar()
        self.date_time_label = QLabel()
        self.date_time_label.setText('date_time')
        self.date_time_label.setAlignment(Qt.AlignRight)
        self.man_version_label = QLabel()
        self.man_version_label.setText(self.get_ui_version())
        self.date_time_label.setAlignment(Qt.AlignRight)
        self.component_label = QLabel()
        self.component_label.setText('')
        self.component_label.setAlignment(Qt.AlignLeft)
        self.statusBar.addWidget(self.component_label)
        self.statusBar.addPermanentWidget(self.man_version_label)
        self.statusBar.addPermanentWidget(self.date_time_label)

        self.setStatusBar(self.statusBar)

    def _menu_file_click_slot(self, sender):
        for component in self.component_list:
            if sender.text() == component['name']:
                try:
                    component['object'].show()
                except:
                    print(component['name'] + 'can not find')
                    pass
            else:
                try:
                    component['object'].hide()
                except:
                    print(component['name'] + 'can not find')
                    pass
        print(sender.text() + 'menu  clicked')

    def _tools_file_click_slot(self, sender):
        print(sender.text() + 'tools')

    def _status_view_info_slot(self, msg):
        self.component_label.setText(msg)

    # 更新时间线程启动
    def _start_date_time(self):
        self._back_time = DateTimeUpdate()
        self._back_time.update_date.connect(self._back_time_update_slot)
        self._back_time.update_date_start()

    def _back_time_update_slot(self, date_time):
        self.date_time_label.setText(date_time)

    def slot_fun(self, signal):
        self.childEvent = signal['Event']


class DateTimeUpdate(QThread):
    update_date = pyqtSignal(object)

    def run(self):
        while True:
            data = QDateTime.currentDateTime()
            current_time = data.toString('yyyy/MM/dd hh:mm:ss')
            self.update_date.emit(str(current_time))
            time.sleep(1)

    def update_date_start(self):
        self.start()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app_path = os.getcwd()
    windows = QMainWindow()
    main = UiMainForm(windows, app_path)
    main.show()
    sys.exit(app.exec())
